package com.easyprogram.article.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.easyprogram.article.pojo.Article;
import com.easyprogram.article.service.ArticleService;
import com.easyprogram.entity.PageResult;
import com.easyprogram.entity.Result;
import com.easyprogram.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
@CrossOrigin
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    //GET /article 文章全部列表
    @RequestMapping(method = RequestMethod.GET)
    //@GetMapping()
    public Result findAll(){
        List<Article> list = articleService.findAll();
        Result result = new Result(true, StatusCode.OK, "查询文章全部列表成功", list);
        return result;
    }

    //GET /article/{articleId} 根据ID查询文章
    @RequestMapping(value = "/{articleId}", method = RequestMethod.GET)
    public Result findById(@PathVariable("articleId") String articleId){
        Article article = articleService.findById(articleId);
        Result result = new Result(true, StatusCode.OK, "根据ID查询文章成功", article);
        return result;
    }

    //POST /article 增加文章
    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Article article){
        articleService.save(article);
        Result result = new Result(true, StatusCode.OK, "增加文章成功");
        return result;
    }

    //PUT /article/{articleId} 修改文章
    @RequestMapping(value = "/{articleId}", method = RequestMethod.PUT)
    public Result updateById(@PathVariable String articleId,
                             @RequestBody Article article){
        //设置id
        article.setId(articleId);
        // 执行修改
        articleService.updateById(article);

        Result result = new Result(true, StatusCode.OK, "修改文章成功");
        return result;
    }

    //DELETE /article/{articleId} 根据ID删除文章
    @RequestMapping(value = "/{articleId}", method = RequestMethod.DELETE)
    public Result deleteById(@PathVariable String articleId){
        articleService.deleteById(articleId);

        Result result = new Result(true, StatusCode.OK, "根据ID删除文章成功");
        return result;
    }

    //POST /article/search/{page}/{size} 文章分页
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    //之前接受文章数据，使用pojo，但是现在根据条件查询
    //而所有的条件都需要进行判断，遍历pojo的所有属性需要使用反射的方式，成本较高，性能较低
    //直接使用集合的方式遍历，这里接受数据改为Map集合
    public Result findByPage(@PathVariable Integer page,
                             @PathVariable Integer size,
                             @RequestBody Map<String,Object> map){
        //根据条件分页查询
        Page<Article> pageData = articleService.findByPage(map, page, size);

        //封装分页返回对象
        PageResult<Article> pageResult = new PageResult<>(
                pageData.getTotal(), pageData.getRecords()
        );

        //返回数据
        Result result = new Result(true, StatusCode.OK, "文章分页查询成功", pageResult);
        return result;
    }

    //测试公共异常处理
    @RequestMapping(value = "/exception", method = RequestMethod.GET)
    public Result test() {
        int a = 1 / 0;

        return null;
    }

    //根据文章id和用户id，建立订阅关系。保存的是文章作者id和用户id的关系
    //POST /article/subscribe
    @RequestMapping(value = "/subscribe", method = RequestMethod.POST)
    public Result subscribe(@RequestBody Map map){
        Boolean flag = articleService.subscribe(map.get("articleId").toString(),
                map.get("userId").toString());
        if(flag == true){
            return new Result(true, StatusCode.OK, "订阅成功");
        } else {
            return new Result(true, StatusCode.OK, "取消订阅成功");
        }
    }

    //根据文章id点赞文章
    //PUT /article/thumbup/{articleId}
    @RequestMapping(value = "/thumbup/{articleId}", method = RequestMethod.PUT)
    public Result thumbup(@PathVariable("articleId") String articleId){
        //TODO 使用JWT鉴权的方式获取当前用户的id
        String userId = "4";

        //查询用户对文章的点赞信息，根据用户id和文章id
        String key = "thumbup_article_" + userId + "_" + articleId;
        Object flag = redisTemplate.opsForValue().get(key);

        //判断查询到的结果是否为空
        if(flag == null){
            //如果为空，表示用户没有点过赞，就可以进行点赞操作
            articleService.thumbup(articleId, userId);
            //点赞成功，保存点赞信息
            redisTemplate.opsForValue().set(key, 1+"");
            return new Result(true, StatusCode.OK, "点赞成功");
        } else {
            //如果不为空，表示用户已经点过赞,取消点赞
            articleService.removeThumbup(articleId);
            redisTemplate.delete(key);
            return new Result(true, StatusCode.OK, "取消点赞成功");

        }
    }

}
